import { reqCartList, reqDeletCart, reqUpdateCheckedByid } from "@/api"
const state = {
    cartList: []
}
const mutations = {
    GETCARTLIST(state, CartList) {
        state.cartList = CartList
    },
}
const actions = {
    //获取购物车列表
    async getCartList({ commit }) {
        let result = await reqCartList()
        if (result.code == 200) { //返回成功标记;
            commit('GETCARTLIST', result.data)
        } else { //返回失败标记
            return Promise.reject(new Error('faile'))
        }
    },
    //删除购物车商品
    async deleteCart({ commit }, skuId) {
        let result = await reqDeletCart(skuId)
        if (result.code == 200) {
            console.log('删除成功');
            return 'ok'
        } else { //返回失败标记
            return Promise.reject(new Error('faile'))
        }
    },
    //修改商品的状态
    async UpdateCheckedByid({ commit }, { skuId, isChecked }) {
        let result = await reqUpdateCheckedByid(skuId, isChecked)
        if (result.code == 200) {
            return 'ok'
        } else { //返回失败标记
            return Promise.reject(new Error('faile'))
        }
    },
    //删除选中的所有商品
    delteAllCheckedCart({ dispatch, getters }) {
        //context小仓库
        //commit【提交mutations】 getters【计算属性】 dispatch【派发action】 state【当前数据仓库】
        //获取购物车的所有商品
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            let promise = item.isChecked == 1 ? dispatch('deleteCart', item.skuId) : ''
            //将每一次返回的promise添加到组织中
            PromiseAll.push(promise)
        });
        /* dispatch('getCartList') */
        //只有全部的p 都成功，返回结果即为成功
        //如果有一个失败的，返回失败结果
        return Promise.all(PromiseAll)
    },
    //修改全部产品状态
    updateAllchecked({ dispatch, state }, isChecked) {
        let PromiseAll = []
        state.cartList[0].cartInfoList.forEach((item) => {
            let promise= dispatch('UpdateCheckedByid', { skuId: item.skuId, isChecked })
            PromiseAll.push(promise)
        })
        //最终返回的结果
        return Promise.all(PromiseAll)
    }
}
const getters = {
    cartList(state) {
        return state.cartList[0] || {}
    },
    cartInfoList() {

    }
}
export default {
    state,
    mutations,
    actions,
    getters
}